﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace MySQL.Db
{
	public class QueryCollection : Collection<Query>
	{
		string connectionString;

		public QueryCollection()
			: this(GollieDb.Gollie)
		{
		}

		public QueryCollection(GollieDb db)
		{
			this.connectionString = DbUtils.GetConnectionString(db);
		}

		public void Add(QueryCollection queries)
		{
			foreach (Query query in queries)
				this.Add(query);
		}

		public void Execute()
		{
			using (ConnectionWithTransaction connection = new ConnectionWithTransaction(this.connectionString))
			{
				try
				{
					for (int i = 0; i < this.Count; i++)
					{
						Query q = this[i];

						using (MySqlCommand command = new MySqlCommand() { CommandText = q.CommandText, CommandType = q.CommandType, Connection = connection.Connection, Transaction = connection.Transaction })
						{
							command.SetParameters(q.Arguments);

							switch (q.ResultType)
							{
								case ResultType.NonQuery: command.ExecuteNonQuery();
									break;
								case ResultType.Scalar: command.ExecuteScalar();
									break;
								default: command.ExecuteReader();
									break;
							}
						}
					}

					connection.Commit();
				}
				catch (MySqlException)
				{
					connection.Rollback();

					throw;
				}
			}
		}
    }
}
